package com.example.guiguiapplicatio.fragment.home;

import android.os.Bundle;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.donkingliang.labels.LabelsView;
import com.example.guiguiapplicatio.api.GetTotalDetailHealthApi;
import com.example.guiguiapplicatio.api.InsertTotalDetailHealthApi;
import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.Interface.GetTotalDetailHealthCallback;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.TotalDetailHealthData;
import com.example.guiguiapplicatio.databinding.FragmentTotalDetailHealthBinding;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PoorFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TotalDetailHealthFragment extends Fragment {
    FragmentTotalDetailHealthBinding binding;
    private LabelsView labelsView;
    private static final String ARG_ID_CARD = "idCard";

    private String idCard;
    private GetTotalDetailHealthApi getTotalDetailHealthApi;
    private InsertTotalDetailHealthApi insertTotalDetailHealthApi;
    private TotalDetailHealthData totalDetailHealthData;
    private String genderSexValue;  // 定义性别变量
    private int householdType;// 定义户籍类型变量
    private int allergyValue = 0;  // 药物过敏史默认为“无”
    private int surgeryValue=0;//手术
    private int exposureHistoryValue = 0; // 暴露史
    private boolean isEditing = false;//boolean变量isEditing来追踪当前的编辑状态
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idCard = getArguments().getString(ARG_ID_CARD);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentTotalDetailHealthBinding.inflate(inflater, container, false);
        View view = binding.getRoot();

        getTotalDetailHealthApi = new GetTotalDetailHealthApi();
        getTotalDetailHealthApi.setGetTotalDetailHealthCallback(getTotalDetailHealthCallback);
        getTotalDetailHealthApi.performRecordDetail(idCard);

        insertTotalDetailHealthApi = new InsertTotalDetailHealthApi();
        insertTotalDetailHealthApi.setTotalDetailHealthCallback(allCallback);

        setEditTextEnabled(false, R.color.black_dim, null);  // 设置为不可编辑状态

        binding.servicBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                Navigation.findNavController(v).navigate(R.id.action_totalDetailHealthFragment_to_recordDetailFragment, bundle);
            }
        });

        binding.comitBtu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publicTotalDetailHealthData();
                Log.d("info", totalDetailHealthData.toString());
                insertTotalDetailHealthApi.performInsertTotalDetailHealth(totalDetailHealthData);
            }
        });
        setOnCheckedChangeListener();
        binding.comitRevise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleEditMode();
            }
        });
        return view;
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }

    GetTotalDetailHealthCallback getTotalDetailHealthCallback = new GetTotalDetailHealthCallback() {
        @Override
        public void onSuccess(ResponseBody<TotalDetailHealthData> dataResponseBody) {
            if (dataResponseBody != null && dataResponseBody.getData() != null) {
                Log.d("info", "响应的数据：" + dataResponseBody.getData());
                TotalDetailHealthData data = dataResponseBody.getData();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //人群分类
                        labelsView = (LabelsView) binding.labels;
                        labelsView.setLabels(data.getListenername());
                        //0 没签约 1 签约中 2 过期
                        if (data.getState() == 0) {
                            binding.etRecordPhone.setText("未签约");
                        } else if (data.getState() == 1) {
                            binding.etRecordPhone.setText("签约中");
                        } else if (data.getState() == 2) {
                            binding.etRecordPhone.setText("已过期");
                        }
                        binding.etRecordName.setText(data.getDoctorname());
                        binding.tvRecordStartSigningDate.setText(data.getTime());
                        binding.etName.setText(data.getName());
                        binding.tvRecordStartSigningDate.setText(data.getTime());
                        binding.tvStartSigningDate.setText(idCard.substring(6,14));
                        binding.etEthnic.setText(data.getNation());
                        // 设置性别
                        if ("男".equals(data.getSex())) {
                            binding.maleRadioButton.setChecked(true);
                        } else if ("女".equals(data.getSex())) {
                            binding.femaleRadioButton.setChecked(true);
                        }
                        binding.etPhone.setText(data.getPhone());
                        binding.etId.setText(data.getIdcard());
                        binding.etDetailedresidence.setText(data.getDetailedresidence());
                        // 设置户籍状态
                        if (data.getRegisteredType() == 1) {
                            binding.maleHousehold.setChecked(true);  // 户籍
                        } else if (data.getRegisteredType() == 0) {
                            binding.femaleHousehold.setChecked(true);  // 非户籍
                        }
                        binding.etBlood.setText(data.getBloodType());
                        binding.etProfession.setText(data.getOccupation());
                        binding.etMarriage.setText(data.getMaritalStatus());
                        binding.etPayment.setText(data.getMedicalPaymentMethod());

                        // 设置药物过敏史
                        if (data.getDrugAllergyHistory() == 0) {
                            binding.radioButtonNone.setChecked(true);
                        } else if (data.getDrugAllergyHistory() == 1) {
                            binding.radioButtonPenicillin.setChecked(true);
                        } else if (data.getDrugAllergyHistory() == 2) {
                            binding.radioButtonOther.setChecked(true);
                        }

                        // 设置暴露史
                        if (data.getExposureHistory() == 0) {
                            binding.radioButtonNone1.setChecked(true);
                        } else if (data.getExposureHistory() == 1) {
                            binding.radioButtonChemicals.setChecked(true);
                        } else if (data.getExposureHistory() == 2) {
                            binding.radioButtonToxic.setChecked(true);
                        } else if (data.getExposureHistory() == 3) {
                            binding.radioButtonRadiation.setChecked(true);
                        }

                        // 设置手术史
                        if (data.getSurgery() == 0) {
                            binding.radioNone.setChecked(true);
                        } else if (data.getSurgery() == 1) {
                            binding.radioYes.setChecked(true);
                        }

                        // 设置原因
                        binding.etReason.setText(data.getReason() != null ? data.getReason() : "");
                    }
                });
            } else {
                Log.d("info", "responseBody" + dataResponseBody.toString());
            }
        }

        @Override
        public void onFailure(String errorMessage) {
        }
    };
    AllCallback allCallback = new AllCallback() {
        @Override
        public void onSuccess(ResponseBody<Object> responseBody) throws ParseException {
            if (responseBody.getCode() == 200) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "保存成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onFailure(String errorMessage) {

        }
    };
    //请求数据
    public void publicTotalDetailHealthData(){
        List<String> selectedLabelsString = new ArrayList<>();

        totalDetailHealthData = new TotalDetailHealthData(
                selectedLabelsString,
                binding.etRecordName.getText().toString(),
                null,
                binding.tvRecordStartSigningDate.getText().toString(),
                idCard,
                binding.etName.getText().toString(),
                binding.etDetailedresidence.getText().toString(),
                binding.etEthnic.getText().toString(),
                binding.etPhone.getText().toString(),
                genderSexValue,
                householdType,
                binding.etBlood.getText().toString(),
                binding.etProfession.getText().toString(),
                binding.etMarriage.getText().toString(),
                binding.etPayment.getText().toString(),
                allergyValue,
                exposureHistoryValue,
                surgeryValue,
                binding.etReason.getText().toString()
        );
    }
    //监听器
    public void setOnCheckedChangeListener(){
        // 设置性别RadioGroup的监听器
        binding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.maleRadioButton) {
                    genderSexValue = "男";  // 男性
                } else if(checkedId == R.id.femaleRadioButton) {
                    genderSexValue = "女";  // 女性
                }
                // Log the genderValue
                Log.d("info", "genderValue: " + genderSexValue);
            }
        });
        // 设置户籍RadioGroup的监听器
        binding.Household.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.maleHousehold) {
                    householdType = 1;  // 户籍
                } else if(checkedId == R.id.femaleHousehold) {
                    householdType = 0;  // 非户籍
                }
                // Log the householdType
                Log.d("info", "householdType: " + householdType);
            }
        });
        // 青霉素
        binding.radioGroupAllergy.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radioButton_none) {
                    allergyValue = 0;  // 无
                } else if (checkedId == R.id.radioButton_penicillin) {
                    allergyValue = 1;  // 青霉素
                } else if (checkedId == R.id.radioButton_other) {
                    allergyValue = 2;  // 其他
                }
                Log.d("info", "allergyValue: " + allergyValue);
            }
        });
        //手术
        binding.radioGroupSurgery.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.radio_none) {
                    // “无”选择，设置值为 0
                    surgeryValue = 0;
                    Log.d("info", "当前手术史选择：" + surgeryValue);
                } else if(checkedId == R.id.radio_yes) {
                    // “有”选择，设置值为 1
                    surgeryValue = 1;
                    Log.d("info", "当前手术史选择：" + surgeryValue);
                }
            }
        });

        // 暴露史单选按钮监听器
        binding.radioGroupExposureHistory.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radioButton_none1) {
                    exposureHistoryValue = 0;
                    Log.d("info", "当前暴露史选择：" + exposureHistoryValue);
                } else if (checkedId == R.id.radioButton_chemicals) {
                    exposureHistoryValue = 1;
                    Log.d("info", "当前暴露史选择：" + exposureHistoryValue);
                } else if (checkedId == R.id.radioButton_toxic) {
                    exposureHistoryValue = 2;
                    Log.d("info", "当前暴露史选择：" + exposureHistoryValue);
                } else if (checkedId == R.id.radioButton_radiation) {
                    exposureHistoryValue = 3;
                    Log.d("info", "当前暴露史选择：" + exposureHistoryValue);
                }
            }
        });
    }
    //修改按钮
    public void toggleEditMode(){
        if (isEditing) {
            setEditTextEnabled(false, R.color.black_dim, null);
            binding.comitRevise.setText("修改");
            isEditing = false;
        } else {
            setEditTextEnabled(true, R.color.black, R.drawable.border_background_health);
            binding.comitRevise.setText("保存");
            isEditing = true;
        }
    }
    private void setEditTextEnabled(boolean isEnabled, int textColor, Integer backgroundDrawable) {
        //名字
        binding.etName.setEnabled(isEnabled);
        binding.etName.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etEthnic.setEnabled(isEnabled);
        binding.etEthnic.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etPhone.setEnabled(isEnabled);
        binding.etPhone.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etId.setEnabled(isEnabled);
        binding.etId.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etDetailedresidence.setEnabled(isEnabled);
        binding.etDetailedresidence.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etBlood.setEnabled(isEnabled);
        binding.etBlood.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etProfession.setEnabled(isEnabled);
        binding.etProfession.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etMarriage.setEnabled(isEnabled);
        binding.etMarriage.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etPayment.setEnabled(isEnabled);
        binding.etPayment.setTextColor(ContextCompat.getColor(getContext(), textColor));
        binding.etReason.setEnabled(isEnabled);
        binding.etReason.setTextColor(ContextCompat.getColor(getContext(), textColor));
        //性别
        binding.maleRadioButton.setEnabled(isEnabled);
        binding.maleRadioButton.setClickable(isEnabled);
        binding.femaleRadioButton.setEnabled(isEnabled);
        binding.femaleRadioButton.setClickable(isEnabled);
        binding.radioGroup.setEnabled(isEnabled);
        binding.radioGroup.setClickable(isEnabled);
        //户籍
        binding.maleHousehold.setEnabled(isEnabled);
        binding.maleHousehold.setClickable(isEnabled);
        binding.femaleHousehold.setEnabled(isEnabled);
        binding.femaleHousehold.setClickable(isEnabled);
        binding.Household.setEnabled(isEnabled);
        binding.Household.setClickable(isEnabled);
        //药物过敏史
        binding.radioButtonNone.setEnabled(isEnabled);
        binding.radioButtonNone.setClickable(isEnabled);
        binding.radioButtonPenicillin.setEnabled(isEnabled);
        binding.radioButtonPenicillin.setClickable(isEnabled);
        binding.radioButtonOther.setEnabled(isEnabled);
        binding.radioButtonOther.setClickable(isEnabled);
        binding.radioGroupAllergy.setEnabled(isEnabled);
        binding.radioGroupAllergy.setClickable(isEnabled);
        //暴露史
        binding.radioButtonNone1.setEnabled(isEnabled);
        binding.radioButtonNone1.setClickable(isEnabled);
        binding.radioButtonChemicals.setEnabled(isEnabled);
        binding.radioButtonChemicals.setClickable(isEnabled);
        binding.radioButtonToxic.setEnabled(isEnabled);
        binding.radioButtonToxic.setClickable(isEnabled);
        binding.radioButtonRadiation.setEnabled(isEnabled);
        binding.radioButtonRadiation.setClickable(isEnabled);
        binding.radioGroupExposureHistory.setEnabled(isEnabled);
        binding.radioGroupExposureHistory.setClickable(isEnabled);
        //手术
        binding.radioNone.setEnabled(isEnabled);
        binding.radioNone.setClickable(isEnabled);
        binding.radioYes.setEnabled(isEnabled);
        binding.radioYes.setClickable(isEnabled);
        binding.radioGroupSurgery.setEnabled(isEnabled);
        binding.radioGroupSurgery.setClickable(isEnabled);

        if (backgroundDrawable != null) {
            binding.etName.setBackgroundResource(backgroundDrawable);
            binding.etEthnic.setBackgroundResource(backgroundDrawable);
            binding.etPhone.setBackgroundResource(backgroundDrawable);
            binding.etId.setBackgroundResource(backgroundDrawable);
            binding.etDetailedresidence.setBackgroundResource(backgroundDrawable);
            binding.etBlood.setBackgroundResource(backgroundDrawable);
            binding.etProfession.setBackgroundResource(backgroundDrawable);
            binding.etMarriage.setBackgroundResource(backgroundDrawable);
            binding.etPayment.setBackgroundResource(backgroundDrawable);
            binding.etReason.setBackgroundResource(backgroundDrawable);

            // ...
        } else {
            binding.etName.setBackground(null);
            binding.etEthnic.setBackground(null);
            binding.etPhone.setBackground(null);
            binding.etId.setBackground(null);
            binding.etDetailedresidence.setBackground(null);
            binding.etBlood.setBackground(null);
            binding.etProfession.setBackground(null);
            binding.etMarriage.setBackground(null);
            binding.etPayment.setBackground(null);
            binding.etReason.setBackground(null);

            // ...
        }
    }
}